/**
 * 
 */
package todolist.activities;

import java.util.Calendar;
import java.util.Date;

import todolist.activities.R;
import todolist.helpers.taskDataSource;
import todolist.structures.Task;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 
 * 
 *
 */
public class EditActivity extends Activity implements OnClickListener{
	
	public taskDataSource datasource;
	public int mYear;
	public int mMonth;
	public int mDay;
	private TextView mDateDisplay;

    Button acceptButton;
    Button cancelButton;
    Button mPickDate;
    Button completeButton;
    Button mapButton;
    Button locationButton;
    RadioGroup type;
    RadioButton work;
    RadioButton personal;
    RadioButton school;
    Location location;
    TextView locationText;
    double lat; 
    double lng;
    protected static LocationManager lm;
    
	static final int DATE_DIALOG_ID = 0;

	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.newscreen);
        
        datasource = new taskDataSource(this);
        
        // Add the buttons
        acceptButton = (Button) findViewById(R.id.acceptButton);
        cancelButton = (Button) findViewById(R.id.cancelButton);
       
        mPickDate = (Button) findViewById(R.id.pickDate);
        type = (RadioGroup) findViewById(R.id.typeGroup);
        work = (RadioButton) findViewById(R.id.workRadio);
        school = (RadioButton) findViewById(R.id.schoolRadio);
        personal = (RadioButton) findViewById(R.id.personalRadio);

        
        // Add the button listeners
        acceptButton.setOnClickListener(this);
        cancelButton.setOnClickListener(this);

        //location services
        lm = (LocationManager) this.getSystemService((Context.LOCATION_SERVICE));
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, locationListener);
        location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		lat = location.getLatitude();
		lng = location.getLongitude();
		locationText = (TextView) findViewById( R.id.textLocation);
		locationText.setText("Location: "+ lng +" " + lat);
		
        //listener for date button
        mPickDate.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(DATE_DIALOG_ID);
            }
        });
        
        //get the current date
        final Calendar c = Calendar.getInstance();
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH);
        mDay = c.get(Calendar.DAY_OF_MONTH);

        // display the current date
	    mDateDisplay = (TextView) findViewById(R.id.dateDisplay);
        updateDisplay();
        
        // Open the context
        TodoList context = ((TodoList) getApplicationContext());
        
        
        // If this is an edit, not a new task, fill in the fields with the old info
        if(context.isNewTask()==false)
        {
        	setContentView(R.layout.editscreen);
        	
        	 // Add the buttons
            acceptButton = (Button) findViewById(R.id.acceptButton);
            cancelButton = (Button) findViewById(R.id.cancelButton);
            mPickDate = (Button) findViewById(R.id.pickDate);
        	completeButton = (Button) findViewById(R.id.completeButton); 
            mapButton = (Button) findViewById(R.id.mapButton); 
            locationButton = (Button) findViewById(R.id.locationButton);
       
        	// Add the button listeners
            completeButton.setOnClickListener(this);
            mapButton.setOnClickListener(this);      
            acceptButton.setOnClickListener(this);
            cancelButton.setOnClickListener(this);
            locationButton.setOnClickListener(this);
            
            //listener for date button
            mPickDate.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    showDialog(DATE_DIALOG_ID);
                }
            });

            // display the current date
    	    mDateDisplay = (TextView) findViewById(R.id.dateDisplay);
            updateDisplay();           
        	
        	// Open the database and find the appropriate task 
        	datasource.open();
        	Task currentTask = datasource.getAllTasks().get(context.getCurrentTaskId()-1);
        	
        	// Match the editText objects with the appropriate field
        	EditText shortDes = (EditText) findViewById( R.id.shortDescripText);
			EditText longDes = (EditText) findViewById( R.id.longDescripText);
			locationText = (TextView) findViewById( R.id.textLocation);
		    // Set the fields to the appropriate value
			shortDes.setText(currentTask.getShortDescription());
			longDes.setText(currentTask.getLongDescription());
			locationText.setText("Location: " + currentTask.getLongitude() +" " + currentTask.getLatitude());
			
			// get selected radio button from radioGroup
			int selectedId = type.getCheckedRadioButtonId();
						
			// find the radiobutton by returned id
	        RadioButton type = (RadioButton) findViewById(selectedId);
	        
			
			//type.setText(currentTask.getTaskType());
			mDateDisplay.setText(currentTask.getDate());
			
			// Close the database
			datasource.close();
        }
	}
	
	// the callback received when the user "sets" the date in the dialog
    private DatePickerDialog.OnDateSetListener mDateSetListener =
            new DatePickerDialog.OnDateSetListener() {

                public void onDateSet(DatePicker view, int year, 
                                      int monthOfYear, int dayOfMonth) {
                    mYear = year;
                    mMonth = monthOfYear;
                    mDay = dayOfMonth;
                    updateDisplay();
                }
            };
            
	protected Dialog onCreateDialog(int id) {
	    switch (id) {
	    case DATE_DIALOG_ID:
	        return new DatePickerDialog(this,
	                    mDateSetListener,
	                    mYear, mMonth, mDay);
	    }
	    return null;
	}
	public void onClick(View v) {

		TodoList context = ((TodoList) getApplicationContext());
		
		switch (v.getId()) {
		
		case R.id.mapButton:
			Intent i = new Intent(getApplicationContext(), MapViewActivity.class);
			i.putExtra("lng", lng);
			i.putExtra("lat", lat);
			startActivity(i);
			break;
			
		case R.id.locationButton:
			//get location
			location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
			lat = location.getLatitude();
			lng = location.getLongitude();
			locationText.setText("Location: "+ lng +" " + lat);

			break;
		
		//Accept Button is clicked
		case R.id.acceptButton:
			EditText shortDes = (EditText) findViewById( R.id.shortDescripText);

			// If "	Add Task" is selected as the short description, reject as invalid
			if (shortDes.equals("	Add Task")==true)
			{
				Toast.makeText(EditActivity.this, "Add Task not a valid short description",
						Toast.LENGTH_LONG).show();
			}
			// If this is an edit, not the creation of a new task,
			// treat as an edit when making database changes
			else if(context.isNewTask()==false)
			{
				// Open the database
				datasource.open();

				// Assign the EditTexts to their appropriate field
				int userID = context.getCurrentUserId();
				EditText longDes = (EditText) findViewById( R.id.longDescripText);
				
				// get selected radio button from radioGroup
				RadioGroup typeGroup = (RadioGroup) findViewById(R.id.typeGroup);
				int selectedId = typeGroup.getCheckedRadioButtonId();
				
				//find the radiobutton by returned id
		        RadioButton type = (RadioButton) findViewById(selectedId);
		        String typeVal= (String) type.getText();
	
				// Edit the desired task
				datasource.editTask(userID, ""+lat, ""+lng, mDateDisplay.getText().toString(),
						shortDes.getText().toString(), longDes.getText().toString(), typeVal, context.getCurrentTaskId()-1);

				// Close the database
				datasource.close();

				// Close the window and return to previous screen
				finish();
				break;
			}
			
			// This is a new task, so treat as a new task when making database changes
			else{

				// Open the database
				datasource.open();

				//Get the id of the current user to store task under his list
				int userID = context.getCurrentUserId();
				
				
				// Parse the info for the new task 
				EditText longDes = (EditText) findViewById( R.id.longDescripText);
				// get selected radio button from radioGroup
				
				int selected = type.getCheckedRadioButtonId();

				// find the radiobutton by returned id
		        RadioButton type = (RadioButton) findViewById(selected);
		        String typeVal= (String) type.getText();

				// Create the new task at the end of the list
				datasource.createTask(userID, ""+lat, ""+lng, mDateDisplay.getText().toString(),
						shortDes.getText().toString(), longDes.getText().toString(), typeVal);

				// Inform the user that the change was made properly
				Toast.makeText(EditActivity.this, "User Task Added",
						Toast.LENGTH_LONG).show();

				// Close the database
				datasource.close();

				// Close the window and return to previous
				finish();
				break;
			}

		case R.id.completeButton:

		
			// Open the database
			datasource.open();

			// Assign the EditTexts to their appropriate field
			EditText shortDesc = (EditText) findViewById( R.id.shortDescripText);
			int userID = context.getCurrentUserId();
			EditText longDes = (EditText) findViewById( R.id.longDescripText);
			RadioGroup typeGroup = (RadioGroup) findViewById( R.id.typeGroup);
			// get selected radio button from radioGroup
			int selectedId = typeGroup.getCheckedRadioButtonId();
			
			// find the radiobutton by returned id
	        RadioButton type = (RadioButton) findViewById(selectedId);
	        String typeVal= (String) type.getText();
	        
			// Complete the desired task
			datasource.completeTask(userID, ""+lat, ""+lng, mDateDisplay.getText().toString(),
				shortDesc.getText().toString(), longDes.getText().toString(), typeVal, context.getCurrentTaskId()-1);

			// Close the database
			datasource.close();

			// Close the window and return to previous screen
			finish();
			break;
		
			
		//Cancel Button is clicked. Return to previous activity
		case R.id.cancelButton:
			finish();
			break;
		}
	}
	
	LocationListener locationListener = new LocationListener() {
		public void onLocationChanged(Location location) {

		}

		public void onProviderDisabled(String arg0) {

		}

		public void onProviderEnabled(String arg0) {
			// TODO Auto-generated method stub

		}

		public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
			// TODO Auto-generated method stub

		}
	};
	
    // updates the date in the TextView
    public String updateDisplay() {
        mDateDisplay.setText(
            new StringBuilder()
                    // Month is 0 based so add 1
                    .append(mMonth + 1).append("-")
                    .append(mDay).append("-")
                    .append(mYear).append(" "));
		return mDateDisplay.getText().toString();
    }
	
	@Override
	protected void onResume() {
		datasource.open();
		super.onResume();
	}

	@Override
	protected void onPause() {
		datasource.close();
		super.onPause();
	}
}
